package com.ndood.payment.core.web.mvc;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.ndood.payment.core.web.fastjson.PaymentJsonFilter;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
	
	@Autowired
	private PaymentJsonFilter paymentJsonFilter;
	
	/**
	 * 静态资源映射
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		String location = "classpath:/static/";
		registry.addResourceHandler("/favicon.ico").addResourceLocations(location + "favicon.ico");
	}
	
	/**
	 * 注册拦截器
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {

	}
	
	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

		/*
		 * 1、需要先定义一个 convert 转换消息对象； 2、添加 fastJson 的配置信息，比如: 是否要格式化返回的Json数据； 3、在
		 * Convert 中添加配置信息; 4、将 convert 添加到 converts 中;
		 */
		// 1、需要先定义一个 convert 转换消息对象；
		FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

		// 2、添加 fastJson 的配置信息，比如: 是否要格式化返回的Json数据；
		FastJsonConfig fastJsonConfig = new FastJsonConfig();
		fastJsonConfig.setSerializerFeatures(
				SerializerFeature.PrettyFormat, 
				SerializerFeature.WriteDateUseDateFormat,
				SerializerFeature.DisableCircularReferenceDetect,
				SerializerFeature.WriteNullStringAsEmpty);
		fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
		// 自定义序列化过滤器
		fastJsonConfig.setSerializeFilters(paymentJsonFilter);

		// 3、处理中文乱码问题
		List<MediaType> fastMediaTypes = new ArrayList<>();
		fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
		fastConverter.setSupportedMediaTypes(fastMediaTypes);

		// 4、在 Convert 中添加配置信息;
		fastConverter.setFastJsonConfig(fastJsonConfig);

		// 5、将 convert 添加到 converts 中;
		converters.add(fastConverter);

	}
	
}

